<template>
  <div class="card-list">
    <a-list
      :grid="{gutter: 24, lg: 3, md: 2, sm: 1, xs: 1}"
      :dataSource="dataSource"
    >
      <a-list-item slot="renderItem" slot-scope="item">
        <template v-if="item.add">
            <a-card hoverable class="upload-card">
                <a-upload-dragger
                    name="file"
                    :multiple="false"
                    @change="handleChange"
                    :file-list="fileList" 
                    :remove="handleRemove" 
                    :before-upload="beforeUpload"
                >
                    <p class="ant-upload-drag-icon">
                        <a-icon type="inbox" style="font-size: 42px;" />
                    </p>
                    <p class="custom-upload-text">
                        点击选择插件文件,然后点击上传插件按钮进行上传
                    </p>
                </a-upload-dragger>
                <div style="height: 30px;" v-if="fileList.length <= 0"></div>
                <template slot="actions" class="ant-card-actions">
                    <a-button
                        type="primary"
                        :size="`small`"
                        :disabled="fileList.length === 0"
                        :loading="uploading"
                        @click="handleUpload"
                        >
                        {{ uploading ? '上传中...' : '上传插件' }}
                    </a-button>
                </template>
            </a-card>
        </template>
        <template v-else>
          <a-card :hoverable="true">
            <a-card-meta >
              <div style="margin-bottom: 3px" slot="title">{{item.name}}</div>
              <a-avatar class="card-avatar" slot="avatar" :src="item.avatar" size="large" />
              <div class="meta-content" slot="description">
                  <div>插件作者: {{item.author}}</div>
                  <div>插件上传时间: {{ dateFormat(item.fixdate) }}</div>
                  <p>插件描述: {{item.describes}}</p>
              </div>
            </a-card-meta>
            <a slot="actions" @click="detail(item.id)">查看</a>
            <a slot="actions" @click="uninstall(item.id)">卸载</a>
          </a-card>
        </template>
      </a-list-item>
    </a-list>
    <a-modal v-model="visible" title="上传插件" on-ok="handleClosed">
        <a-steps :current="stepNumber" direction="vertical" :status="stepStatus">
            <a-step :description="uploadMsg">
                <!-- <span slot="title">Finished</span> -->
                <template slot="title">
                    上传插件 <span><a-icon v-if="uploadLoading" type="redo" spin /></span>
                </template>
            </a-step>
            <a-step>
                <template slot="title">
                    校验插件 <span><a-icon  v-if="checkLoading" type="redo" spin /></span>
                </template>
                <div slot="description">
                    <ul v-if="checkResult" style="max-height: 200px; overflow: auto;">
                        <li v-for="(item, index) in checkResult.data" :key="index">
                            <div>功能名称：<span>{{ item.name }}</span></div>
                            <!--<div>功能地址：<span>{{ item.url }}</span></div>-->
                            <div>功能描述：<span>{{ item.describe }}</span></div>
                            <div>变更状态：<span :style="optState(item.opt).class">{{ optState(item.opt).text }}</span></div>
                        </li>
                    </ul>
                    <span v-if="isCancel" :style="fontColor">{{ checkResult && checkResult.msg }}</span>
                    <div v-if="checkResult && isCancel">
                        <a-button type="link" @click="visible = false">
                            取消
                        </a-button>
                        <a-button type="link" v-if="showInstall" @click="installPlugin">
                            安装
                        </a-button>
                    </div>
                </div>
            </a-step>
            <a-step title="安装成功"/>
        </a-steps>
        <template slot="footer" style="text-align: center;">
            <a-button key="back" @click="handleClosed">
                关闭
            </a-button>
        </template>
    </a-modal>
    
  </div>
</template>

<script>
import { uploadPlugin, checkPlugin, installPlugin, uninstallPlugin, getPluginList } from '@/services/plugins'
import { STATE_SUCCESS } from '@/services/api'
import moment from 'moment'

const columns = [
  {
    title: '插件名称',
    dataIndex: 'name'
  },
  {
    title: '插件版本',
    dataIndex: 'version'
  },
  {
    title: '描述',
    dataIndex: 'describes'
  },
  {
    title: '插件作者',
    dataIndex: 'author'
  },
  {
    title: '插件图标',
    dataIndex: 'icon'
  },
  {
    title: '更新时间',
    dataIndex: 'fixdate',
    sorter: true
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
]

/**功能校验文字格式 */
const optstyle = {
    add: {text:'新建',class:'color:#28FF28;font-weight:bold'},
    update: {text:'更新',class:'color:73BF00;font-weight:bold'},
    del: {text:'删除',class:'color:red;font-weight:bold'}
}

export default {
    name: 'CardList',
    data () {
        return {
            dataSource: [],
            advanced: true,
            columns: columns,
            selectedRows: [],
            fileList: [],
            uploading: false,
            detailData: null,
            uploadLoading: false,
            checkLoading: false,
            stepNumber: 0,
            visible: false,
            uploadMsg: "",
            checkResult: undefined,
            isCancel: true,
            showInstall: true,
            fontColor:'color:green',
            optclass: '',
            stepStatus: 'process' // wait|process|finish|error
        }
    },
    // mounted: {

    // },
    methods: {
        optState(opt){
            if(opt){
                let opt_class = optstyle[opt].class;
                let opt_text = optstyle[opt].text;
                return {class:opt_class,text:opt_text};
            }else{
                return {class:'',text:''};
            }
        },
        initmsg(){
            this.showInstall = true,
            this.fontColor='color:green'
        },
        handleChange(info) {
            const status = info.file.status;
            if (status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (status === 'done') {
                this.$message.success(`${info.file.name} file uploaded successfully.`);
            } else if (status === 'error') {
                this.$message.error(`${info.file.name} file upload failed.`);
            }
        },
        handleRemove(file) {
            const index = this.fileList.indexOf(file);
            const newFileList = this.fileList.slice();
            newFileList.splice(index, 1);
            this.fileList = newFileList;
        },
        beforeUpload(file) {
            this.fileList = [file];
            return false;
        },
        // 上传插件
        uploadPlugin (formData) {
            this.uploadLoading = true;
            this.initmsg();
            return new Promise((resolve, reject) => {
                uploadPlugin(formData).then(res => {
                    let { data, msg, state } = res.data.result.dataresult;
                    if (state == STATE_SUCCESS) {
                        this.fileList = []
                        this.stepNumber = 1
                        resolve(data.filename)
                    } else {
                        this.stepStatus = 'error';
                        reject(res)
                    }
                    this.uploading = false;
                    this.uploadLoading = false;
                    this.uploadMsg = msg;
                }).catch(err => {
                    console.log(err)
                    this.uploading = false;
                    this.uploadLoading = false;
                    this.stepStatus = 'error'
                    reject(err)
                })
            })
        },
        // 校验插件
        checkPlugin (filename) {
            return new Promise((resolve, reject) => {
                checkPlugin(filename).then(res => {
                        console.log(res.data);
                        let { state } = res.data.result;
                        this.checkResult = res.data.result;
                        this.checkResult['filename'] = filename;
                        this.checkResult['state'] = state;
                        this.stepStatus = 'finish';
                        if(state == '3'){
                            this.showInstall = false;
                            this.fontColor = 'color:red';
                        }
                        resolve({filename, state})
                    }).catch(err => {
                        console.log(err);
                        reject(err);
                        this.stepStatus = 'error'
                    })
            }) 
        },
        // 安装插件
        installPluginConfirm (res) {
            let { result } = res
            let that = this;
            return new Promise((resolve, reject) => {
                this.$confirm({
                    title: '提示',
                    content: result.msg,
                    okText: '确认',
                    cancelText: '取消',
                    onOk() {
                        resolve({filename: res.filename, state: result.state})
                    },
                    onCancel() {
                        that.$destroyAll();
                        reject(undefined)
                    },
                });
            })
        },
        installPlugin () {
            if (this.checkResult.state != 3) {
                installPlugin({
                    filename: this.checkResult.filename,
                    state: this.checkResult.state
                }).then(res => {
                    let { result } = res.data
                    if (result.state == "200") {
                        this.stepNumber = 2
                        this.stepStatus = 'finish'
                        this.isCancel = false;
                    } else {
                        this.$message.error('install error.');
                    }
                }).catch(err => {
                    console.warn(err)
                })
            }
        },
        // 卸载
        uninstall (id) {
            let that = this
            this.$confirm({
                title: '提示',
                content: "确认要卸载该插件吗？\n本插件所有功能已关联的菜单将被删除",
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                    uninstallPlugin(id).then(res => {
                        console.log(res)
                        let { state } = res.data.result;
                        if (state === '200') {
                            this.$message.success("成功卸载");
                        } else  {
                            this.$message.error("卸载失败");
                        }
                        this.getPluginList()
                    })
                },
                onCancel() {
                    that.$destroyAll();
                },
            });
            
        },
        // 查看
        detail (id) {
            this.$router.push({
                path: '/plugin_detail',
                query: { id }
            })
        },
        // 操作提示
        openNotificationWithIcon(res) {
            let type = res['result']['code'] == 200 ? 'success' : 'error';
            this.$notification[type]({
                message: 'Notification Title',
                description: '',
            });
        },
        // 插件上传
        handleUpload() {
            const { fileList } = this;
            const formData = new FormData();
            fileList.forEach(file => {
                formData.append('files[]', file);
            });
            this.uploading = true;
            this.showModal()
            this.uploadPlugin(formData).then(res => {
                return this.checkPlugin(res)
            }).catch(err => {
                console.log(err)
            })
        },
        // 查询插件列表或明细
        getPluginList (id) {
            getPluginList({ id }).then(res => {
                let { result } = res['data']
                if (!id) {
                    this.dataSource = [{add: true}];
                    this.dataSource.push(...result.data)
                } else {
                    this.detailData = res
                }
            })
        },
        showModal() {
            this.visible = true;
        },
        handleClosed(e) {
            console.log(e, "handleClosed");
            this.visible = false;
            this.stepStatus = 'process';
            this.stepNumber = 0;
            this.checkResult = undefined;
            this.isCancel = true;
            this.getPluginList()
        },
        /*日期处理*/
        dateFormat:function(date){
            if(date === undefined){
                return ''
            }
            return moment(date).format("YYYY-MM-DD HH:mm:ss")
        },
    },
    created () {
        this.dataSource = [{add: true}];
        this.getPluginList()
    }
}
</script>

<style lang="less" scoped>
    .card-avatar {
        width: 48px;
        height: 48px;
        border-radius: 48px;
    }
    .new-btn{
        border-radius: 2px;
        width: 100%;
        height: 187px;
    }
    .meta-content{
        position: relative;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        height: 64px;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
    }
    ::v-deep .upload-card .ant-card-body {
        padding: 0px;
    }
    ::v-deep .upload-card .ant-upload.ant-upload-drag p.ant-upload-drag-icon {
        margin-bottom: 9px;
    }
    .custom-upload-text {
        font-size: 14px;
        color: rgba(0,0,0, 0.45);
    }
</style>
